package hy;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class ZKClient {
    String url="192.168.188.100:2181";
    int timeout=20000;
    ZooKeeper cli;

    @Before
    public void init()throws Exception{
        cli=new ZooKeeper(url, timeout, new Watcher() {
            //1.在zk发送通知后，会执行
            //2.初次连接成功后，会主动调用
            public void process(WatchedEvent watchedEvent) {
                List<String> childs;
                System.out.println("==========begin=========");
                try{
                    childs=cli.getChildren("/",true);
                    for(String c:childs){
                        System.out.println(c);
                    }
                    System.out.println("=========end==============");

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    @Test
    public void createNode()throws Exception{
        Thread.sleep(3000);
        String path=cli.create("/servers","hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("path:"+path);
        Thread.sleep(Integer.MAX_VALUE);
    }
    @Test
    public void deleteModifyRead()throws Exception{
        Stat s=cli.exists("/servers",false);
        System.out.println("存在servers?"+(s!=null));
        int version=s.getVersion();
        System.out.println("servers的版本:"+version);
//        if(s!=null){
//            cli.delete("/servers",version);-----------+

//        }
        //下面是修改
        //cli.setData("/servers","嘿嘿".getBytes(),version);
//        //读取
        System.out.println(new String(cli.getData("/servers", false, null)));
    }
}